define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shops/shop/index' + location.search,
                    add_url: 'shops/shop/add',
                    edit_url: 'shops/shop/edit',
                    // del_url: 'shops/shop/del',
                    multi_url: 'shops/shop/multi',
                    import_url: 'shops/shop/import',
                    table: 'shop',
                },

                exportOptions: {
                    ignoreColumn: [0, 2,'operate'],
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search:false,
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: '店铺id'},
                        {field: 'logo_pic', title: 'LOGO', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'shop_name', title: '店铺名称', operate: 'LIKE', align: 'left',halign:"center"},
                        {field: 'shop_type', title: '外卖平台', searchList: {"1":__('Shop_type 1'),"2":__('Shop_type 2'),"3":"京东"}, formatter: Table.api.formatter.normal},
                        {field: 'nopay', title: '待支付', operate: false},
                        // {field: 'category_no_text', title: __('Category_id'), operate: false},
                        {field: 'admin.nickname', title: '业务员',searchList: Config.salesmanList},
                        // {field: 'contact_user', title: '联系人', operate: 'LIKE'},
                        {field: 'phone', title: '商家号码', operate: 'LIKE'},
                        {field: 'address', title: '店铺定位', operate: 'LIKE', align: 'left',halign:"center"},
                        {field: 'is_auth', title: '商家授权状态', searchList: {"0":'未授权',"1":'已授权'}, formatter: Table.api.formatter.status},
                        {field: 'submission_channel', title: '店铺在线状态', searchList: {"6":'不在线',"5":'在线'}, formatter: Table.api.formatter.status,custom:{"6": 'gray', "5": 'success'}},
                        {field: 'shop_status', title: __('Status'), searchList: {"-1":__('Status -1'),"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        {field: 'create_dt', title: __('Createtime'),operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'update_dt', title: __('Updatetime'),operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                        buttons: [
                            {
                                name: 'bill',
                                text: '账单',
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'shops/shop/bill',
                                // extend: 'data-area=["500px","500px"]',
                                visible: function(row){
                                    if (1 == row.shop_status) return ! 0
                                }, 
                            },
                            {
                                name: 'edit',
                                text: '编辑',
                                icon: 'fa',
                                classname: 'btn btn-xs btn-success btn-editone',
                                url: 'shops/shop/edit'
                            },
                            {
                                name: 'copy',
                                text: '复制授权链接',
                                icon: 'fa',
                                classname: 'btn btn-xs btn-info btn-dialog',
                                url: 'shops/shop/copy',
                                visible: function(row){
                                    if ("1" == row.shop_type) return ! 0
                                }, 
                            },
                        ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shops/shop/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'delete_dt',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'shops/shop/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'shops/shop/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
            $("[data-toggle='addresspicker']").data("callback", function(res){
                //其中res则是包含了address/lat/lng等信息的JSON对象
                console.log(res)
            });
            $("#city-picker").on("cp:updated", function() {
                var citypicker = $(this).data("citypicker");
                var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
                $("#code").val(code);
            });
            $('#c-address1').on('change',function (e) {
                var address = $('#c-address1').val();
                $('#c-address').val(address)
                $.ajax({
                    url:"/hFtNsJROTk.php/shops/shop/getLocation?address="+address,
                    success:function(result){
                        console.log(result)
                        if (result.data!=undefined) {
                            $('#c-lat').val(result.data.lat)
                            $('#c-lng').val(result.data.lng)
                        }
                    }
                    // url:"https://restapi.amap.com/v3/geocode/geo?key=568d9db7d205114cfd05cfea2b908bac&address="+address,
                    // success:function(result){
                    //     if (result.geocodes[0].location!=undefined) {
                    //         var arr = result.geocodes[0].location.split(',')
                    //         $('#c-lat').val(arr[1])
                    //         $('#c-lng').val(arr[0])
                    //     }
                    // }
                })
            });
            // 判断店铺有没有重复
            $('#c-have_uid').change(function () {
                var shop_name = $('#c-shop_name').val();
                var shop_type = $('#c-shop_type').val();
                $.ajax({
                    url:"/hFtNsJROTk.php/shops/shop/isShopRepeat",
                    data: { shop_name: shop_name,shop_type:shop_type },
                    success:function(result){
                        console.log(result)
                        if (result.code===0) {
                            Toastr.error(result.msg);
                        }
                    }
                })
            })
            // $(document).on("click","#c-has_qrcode",function(){
            //     var has_qrcode = $('#c-has_qrcode').prop("checked");
            //     if (has_qrcode==false) {
            //         $('#qrcode_pic').hide();
            //     } else {
            //         $('#qrcode_pic').show();
            //     }
            // });
        },
        edit: function () {
            Controller.api.bindevent();
            $("[data-toggle='addresspicker']").data("callback", function(res){
                //其中res则是包含了address/lat/lng等信息的JSON对象
                console.log(res)
            });
            $("#city-picker").on("cp:updated", function() {
                var citypicker = $(this).data("citypicker");
                var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
                $("#code").val(code);
            });
            $('#c-address1').on('change',function (e) {
                var address = $('#c-address1').val();
                $('#c-address').val(address)
                $.ajax({
                    url:"/hFtNsJROTk.php/shops/shop/getLocation?address="+address,
                    success:function(result){
                        console.log(result)
                        if (result.data!=undefined) {
                            $('#c-lat').val(result.data.lat)
                            $('#c-lng').val(result.data.lng)
                        }
                    }
                })
            })
            // $(document).on("click","#c-has_qrcode",function(){
            //     var has_qrcode = $('#c-has_qrcode').prop("checked");
            //     if (has_qrcode==false) {
            //         $('#qrcode_pic').hide();
            //     } else {
            //         $('#qrcode_pic').show();
            //     }
            // });
            // 判断店铺有没有重复
            // $('#c-have_uid').change(function () {
            //     var shop_name = $('#c-shop_name').val();
            //     var shop_type = $('#c-shop_type').val();
            //     $.ajax({
            //         url:"/hFtNsJROTk.php/shops/shop/isShopRepeat",
            //         data: { shop_name: shop_name,shop_type:shop_type },
            //         success:function(result){
            //             console.log(result)
            //             if (result.code===0) {
            //                 Toastr.error(result.msg);
            //             }
            //         }
            //     })
            // })
        },
        bill: function () {
            Controller.api.bindevent();
            $(document).on("click","#copy-link",function(){
                var url = $('#url').val();
                var oInput = document.createElement('input');
                oInput.value = url;
                document.body.appendChild(oInput);
                oInput.select(); // 进择对家
                document.execCommand("Copy"); // 执行浏览器复制命分
                oInput.className = 'oInput';
                oInput.style.display= 'none';
                Layer.msg('复制链接成功:'+url);
                // 为表格绑定事件
            });
        },
        addplay: function () {
            Controller.api.bindevent();
            // Form.api.bindevent($("form[role=form]"), function(data, ret){
            //     //如果我们需要在提交表单成功后做跳转，可以在此使用location.href="链接";进行跳转
            //     // window.setTimeout(function(){
            //         Backend.api.addtabs('shops/play','活动列表');
            //         //或者刷新当前页面两者选其一
            //         window.parent.location.reload();
            //     // },500);
            //     // Toastr.success("成功");
            // }, function(data, ret){
            //       // Toastr.success("失败");
            // }, function(success, error){
            //     //bindevent的第四个参数为提交前的回调
            //     //如果我们需要在表单提交前做一些数据处理，则可以在此方法处理
            //     //注意如果我们需要阻止表单，可以在此使用return false;即可
            //     //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
            //     //Form.api.submit(this, success, error);
            //     // return false;
            // });
                $(document).on("change", "#c-shop_no", function(e){
                    var val = $('#c-shop_no').val();
                    $.ajax({
                        url:"/hFtNsJROTk.php/shops/play/nopay",
                        data: { shop_no: val },
                        success:function(result){
                            $('#c-start_time_str').val(result.data.startstr)
                            $('#c-end_time_str').val(result.data.endstr)
                            $('#nopay').val(result.data.nopay)
                            $('#c-address').val(result.data.address)
                            $('#c-shop_type').val(result.data.shop_type)
                            $('#c-service_amt').val(result.data.service_amt)
                            $('#c-qrcode img').attr('src',result.data.domain+result.data.qrcode)
                            $('#channel').attr('data-serviceamt',result.data.shop_serviceamt)
                            var serviceamt = $('#channel').attr('data-serviceamt')
                            serviceamt = JSON.parse(serviceamt)
                            if (parseInt($('#c-user_pay').val())>0 && parseInt($('#c-shop_settlement').val())>0) {
                                var mf = ''
                                for (var i = serviceamt.length - 1; i >= 0; i--) {
                                    if (serviceamt[i].channel_name=='吃喝不愁') {
                                        var f=parseInt($('#c-user_pay').val())-serviceamt[i].service_amt
                                        mf='满'+parseInt($('#c-user_pay').val())+'返'+f
                                    }
                                }
                                console.log(mf)
                                $('#channel .flex').find('input').eq(0).val(mf)
                            }
                        }
                    })
                });

        },
        copy: function () {
            Controller.api.bindevent();
            // $(document).on("click","#copy-link1",function(){
            //     var url = $('#url1').val();
            //     var oInput = document.createElement('input');
            //     oInput.value = url;
            //     document.body.appendChild(oInput);
            //     oInput.select(); // 进择对家
            //     document.execCommand("Copy"); // 执行浏览器复制命分
            //     oInput.className = 'oInput';
            //     oInput.style.display= 'none';
            //     Layer.msg('复制链接成功:'+url);
            //     // 为表格绑定事件
            // });
            $(document).on("click","#copy-link2",function(){
                var shopname = $('#copy-link2').attr('data-id')
                var url = $('#url2').val();
                var oInput = document.createElement('input');
                oInput.value = shopname+'：'+url;
                document.body.appendChild(oInput);
                oInput.select(); // 进择对家
                document.execCommand("Copy"); // 执行浏览器复制命分
                oInput.className = 'oInput';
                oInput.style.display= 'none';
                Layer.msg('复制链接成功:'+url);
                // 为表格绑定事件
            });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $(document).on("change", "input[name='row[times_limit]']", function(e){
                    var val = $("input[name='row[times_limit]']:checked").val();
                    if (val==1) {
                        $('#xdcs').show();
                    } else {
                        $('#xdcs').hide();
                    }
                });
                $(document).on("change", "#c-play_type", function(e){
                    var val = $("#c-play_type").val();
                    if (val==2) {
                        $('#is_qcsc').show();
                        $('#user_pay').hide();
                    } else {
                        $('#is_qcsc').hide();
                        $('#user_pay').show();
                    }
                });
                $(document).on("change", "#c-shop_type", function(e){
                    var val = $("#c-shop_type").val();
                    if (val==2) {
                        $('#dpzxelm').show();
                        $('#dpzxelmlabel').show();
                        $('#dpzxelmcheckbox').show();
                    } else {
                        $('#dpzxelm').hide();
                        $('#dpzxelmlabel').hide();
                        $('#dpzxelmcheckbox').hide();
                    }
                });
            }
        }
    };
    return Controller;
});
